package org.xiaoxiao.servlet;

import org.xiaoxiao.dao.BookVoteDao;
import org.xiaoxiao.pojo.Book;
import org.xiaoxiao.pojo.VoteRecord;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/records")
public class RecordsServlet extends HttpServlet {
    private final BookVoteDao dao = new BookVoteDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 检查管理员登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("admin") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 获取所有投票记录
        List<VoteRecord> records = dao.getAllVoteRecords();

        // 创建书籍ID到书籍对象的映射
        Map<String, Book> booksMap = new HashMap<>();
        for (Book book : dao.getAllBooks()) {
            booksMap.put(book.getId(), book);
        }

        request.setAttribute("records", records);
        request.setAttribute("booksMap", booksMap);
        request.getRequestDispatcher("/records.jsp").forward(request, response);
    }
}
